import React, { Component } from 'react';
import './demo1.css'

class Comment extends Component {
    // list传给评论列表组件，当list发生改变，会自动触发评论列表组件更新
    state = { list: [{ user: '香奈儿', txt: '好品牌' }] }
    // 定义方法传给发表评论组件
    receiveCinfo = (cinfo) => {
        let list = this.state.list;
        list.unshift(cinfo);
        this.setState({ list })
    }
    render() {
        return (<div className="box">
            <PublishComment publish={this.receiveCinfo}></PublishComment>
            <CommentList list={this.state.list}></CommentList>
        </div>);
    }
}

export default Comment;


// 1.0 发表评论组件
class PublishComment extends Component {
    state = {
        cinfo: { user: '', txt: '' }
    }
    publish = () => {
        this.props.publish(this.state.cinfo);
        this.setState({ cinfo: { user: '', txt: '' } })
    }

    Change = (e) => {
        // 1.0 获取到当前元素的value值
        let value = e.target.value;
        // 2.0  将原来的状态属性cinfo取出来
        let cinfo = this.state.cinfo;  // { user: '', txt: '' }
        // 给对象中的user属性进行赋值
        let key = e.target.name;
        cinfo[key] = value;  // { user: 'abc', txt: '' }
        // 3.0 调用this.setState修改回去
        this.setState({ cinfo })
    }
    render() {
        return (<div className="top">
            <input type="text" name="user" placeholder="请输入评论人" className="mg"
                value={this.state.cinfo.user} onChange={this.Change} />
            <textarea name="txt" id="" cols="30" rows="10" placeholder="请输入评论内容" className="mg"
                value={this.state.cinfo.txt} onChange={this.Change}></textarea>
            <button className="mg" onClick={this.publish} >发表评论</button>
        </div>);
    }
}

// 2.0 评论列表组件
class CommentList extends Component {

    render() {
        return (<div className="bottom">
            {
                // 2.0 遍历props中的list数组生成评论列表
                this.props.list.map((item, index) => (
                    <ul key={index}>
                        <li>评论人：{item.user}</li>
                        <li>评论内容：{item.txt}</li>
                    </ul>
                ))
            }
        </div>);
    }
}

// function CommentList(props) {
//     return (<div className="bottom">
//         {
//             // 2.0 遍历props中的list数组生成评论列表
//             props.list.map((item, index) => (
//                 <ul key={index}>
//                     <li>评论人：{item.user}</li>
//                     <li>评论内容：{item.txt}</li>
//                 </ul>
//             ))
//         }
//     </div>);
// }